
import { assetManager } from "cc"

import { AssetType } from "./Enums";
import { Global } from "./Global";
import { ResourcePool } from "./ResourcePool";

export default class ResourceManger {
    private bundle_map: Object = {};
    public  clip_map = {};

    private static rm: ResourceManger = null;
    public static get instance() {
        if (!this.rm) {
            this.rm = new ResourceManger();
        }
        return this.rm;
    }


    public async load_bundle(name:string, ratio: number = 0): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            assetManager.loadBundle(name, (e: any, bundle: any) => {
                if (e) {
                    console.error(name + " --------------------------load errors>>>", e)
                } else {
                   this.bundle_map[name] = bundle;
                    console.log(name  + " load success");
                    Global.loading_rate = Global.loading_rate + ratio;
                    resolve && resolve();
                }
            })
        })
    }



    public async load_resource(name: string, type: any, ratio: number = 0): Promise<void> {
        let arr:number[] = [];
        return new Promise<void>((resolve, reject) => {
            this.bundle_map[name].loadDir(type.path, type.type, (finished: number, total: number) => {
                let date = ratio * finished / total;
                arr.push(date);
                if(arr.length ==  1){
                    Global.loading_rate = Global.loading_rate + date;
                }else{
                    Global.loading_rate = Global.loading_rate + (arr[arr.length-1] - arr[arr.length-2]);
                }
                // console.log("date >>",date," Global.loading_rate>",Global.loading_rate);
            }, (e: any, assets: any[]) => {
                if (e) {
                    console.error("load_resource error >>>", e);
                    resolve && resolve();
                }
                assets.forEach(element => {
                    switch (type) {
                        case AssetType.Prefab:
                            ResourcePool.instance.set_prefab(element.data.name, element);
                            //  console.log("prefab>> "+element.data.name + " ")
                            break;
                        case AssetType.Sound:
                            this.clip_map[element.name] = element;
                            //  console.log("sound>> "+ element.name + " ")
                            break;
                    }
                });
                console.log(name + ">>" + type.path + "loaded success")
                resolve && resolve();
            })
        })
    }

    public get_clip(name: string) {
        return this.clip_map[name];
    }

}